package com.xiaochong.tir.manager.controller;

import com.github.pagehelper.PageInfo;
import com.xiaochong.service.common.config.redis.RedisServer;
import com.xiaochong.tir.common.data.po.CurrencyInfo;
import com.xiaochong.tir.common.data.po.ExchangeInfo;
import com.xiaochong.tir.common.data.po.ExchangeTransactionpairMiddle;
import com.xiaochong.tir.common.data.po.TransactionPair;
import com.xiaochong.tir.common.util.RedisKeysUtils;
import com.xiaochong.tir.manager.service.CurrencyInfoService;
import com.xiaochong.tir.manager.service.ExchangeInfoService;
import com.xiaochong.tir.manager.service.ExchangeTransactionpairMiddleService;
import com.xiaochong.tir.manager.service.TransactionPairService;
import com.xiaochong.tir.manager.util.ManagerVersion;
import com.xiaochong.tir.manager.util.ReturnResult;
import com.xiaochong.tir.manager.util.SessionUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;

/**
 * Created by admin on 2018/5/30.
 * 交易对管理
 */
@Controller
@RequestMapping(value= ManagerVersion.API_V1_PREFIX+"trading/")
@Api("交易对管理")
public class TransactionPairController {

    @Autowired
    private TransactionPairService transactionPairService;
    @Autowired
    private ExchangeTransactionpairMiddleService exchangeTransactionpairMiddleService;
    @Autowired
    private CurrencyInfoService currencyInfoService;
    @Autowired
    private RedisServer redisServer;

    /**
     * 列表页
     * @return
     */
    @GetMapping("trapage")
    public String tradingList(){
        return "/transactionpair/transactionlist";
    }

    /**
     * 交易对查询
     * @param transactionPair
     * @param pageSize
     * @param pageIndex
     * @return
     */
    @ApiOperation(value = "查询交易对列表",notes = "交易对表")
    @PostMapping("tralist")
    @ResponseBody
    public ReturnResult<TransactionPair> getTransactionList(TransactionPair transactionPair,
                                                            @RequestParam("limit") Integer pageSize,
                                                            @RequestParam("page")Integer pageIndex){
        PageInfo<TransactionPair> list = transactionPairService.selectByentityList(transactionPair,pageSize,pageIndex);
        ReturnResult<TransactionPair> result = new ReturnResult<TransactionPair>(0,"成功",list.getList(),list.getTotal());
        return result;
    }

    /**
     * /新增页面
     * @return
     */
    @GetMapping("addtrapage")
    public String addTransactionPage(Model model){
        CurrencyInfo info = new CurrencyInfo();
        //所有货币
        List<CurrencyInfo> infos =  currencyInfoService.selectByEntityList(info);
        model.addAttribute("infos",infos);
        //法币
        info.setFrenchCurrency(true);
        List<CurrencyInfo> enNames = currencyInfoService.selectByEntityList(info);
        model.addAttribute("enNames",enNames);

        return "/transactionpair/cretransaction";
    }

    /**
     * /新增交易对
     * @param transactionPair
     * @return
     */
    @ApiOperation(value = "新增交易对",notes = "交易对表")
    @PostMapping("addtransaction")
    @ResponseBody
    public Object addTransaction(TransactionPair transactionPair){
        redisServer.set(RedisKeysUtils.LOGINNAME,"新增交易对");
        try{
            //全部转为大写
            transactionPair.setTransactionName(transactionPair.getTransactionName().toUpperCase());
            transactionPair.setEnName(transactionPair.getEnName().toUpperCase());
            TransactionPair pair = transactionPairService.selectByEntity(transactionPair);
            if(null != pair){
                return new ReturnResult<TransactionPair>(-1,"交易对已存在",1,1);
            }
            transactionPair.setCreateTime(new Date());
            //新增交易对表
            transactionPairService.insertTransaction(transactionPair);
            return new ReturnResult<TransactionPair>(0,"成功",1,1);
        }catch (Exception e){
            e.printStackTrace();
            return new ReturnResult<TransactionPair>(-1,"添加失败",1,1);
        }
    }

    /**
     * 修改交易对
     * @param transactionPair
     * @return
     */
    @ApiOperation(value = "修改交易对",notes = "修改交易对")
    @PostMapping("updateTransaction")
    @ResponseBody
    public Object updateTransaction(TransactionPair transactionPair){
        redisServer.set(RedisKeysUtils.LOGINNAME,"修改交易对");
        TransactionPair pair = new TransactionPair();
        pair.setEnName(transactionPair.getEnName());
        pair.setTransactionName(transactionPair.getTransactionName());
        pair = transactionPairService.selectByEntity(pair);
        if(null != pair){
            return new ReturnResult<TransactionPair>(-1,"交易对已存在",1,1);
        }
        //修改前数据
        TransactionPair old =transactionPairService.selectByPrimaryKey(transactionPair.getId());
        //修改时间
        transactionPair.setUpdateTime(new Date());
        //全部转为大写
        transactionPair.setTransactionName(transactionPair.getTransactionName().toUpperCase());
        transactionPair.setEnName(transactionPair.getEnName().toUpperCase());
        transactionPairService.updateByPrimaryKey(transactionPair,old);
        //修改中间表
        try {
            ExchangeTransactionpairMiddle exchangeTransactionpairMiddle=new ExchangeTransactionpairMiddle();
            exchangeTransactionpairMiddle.setTransactionId(transactionPair.getId());
            exchangeTransactionpairMiddle.setTransactionName(transactionPair.getTransactionName()+"/"+transactionPair.getEnName());
            exchangeTransactionpairMiddle.setTransactionAlias(transactionPair.getTransactionName()+"/"+transactionPair.getEnName());
            exchangeTransactionpairMiddle.setUpdateTime(new Date());
            exchangeTransactionpairMiddleService.updateByName(exchangeTransactionpairMiddle);
            return new ReturnResult<TransactionPair>(0,"修改成功",1,1);
        }catch (Exception e){
            e.printStackTrace();
            return new ReturnResult<TransactionPair>(-1,"修改失败",1,1);
        }
    }

    /**
     * 修改页面
     * @param id
     * @param model
     * @return
     */
    @GetMapping("editTransaction")
    public String editTransaction(@RequestParam("id") Integer id,Model model){
        TransactionPair transactionPair =transactionPairService.selectByPrimaryKey(id);
        model.addAttribute("tra",transactionPair);
        CurrencyInfo info = new CurrencyInfo();
        //所有货币
        List<CurrencyInfo> infos =  currencyInfoService.selectByEntityList(info);
        model.addAttribute("infos",infos);
        //法币
        info.setFrenchCurrency(true);
        List<CurrencyInfo> enNames = currencyInfoService.selectByEntityList(info);
        model.addAttribute("enNames",enNames);

        return "/transactionpair/edittrapage";
    }

    /**
     * 删除所有同名交易对
     * @param id
     * @return
     */
    @ApiOperation(value = "删除交易对",notes = "同时也删除中间表同名交易对")
    @PostMapping("deltransaction")
    @ResponseBody
    public Object deltransaction(@RequestParam("id")Integer id){
        try{
            redisServer.set(RedisKeysUtils.LOGINNAME,"删除交易对");
            TransactionPair pair = new TransactionPair();
            pair.setId(id);
            transactionPairService.delTransaction(pair);
            ExchangeTransactionpairMiddle middle = new ExchangeTransactionpairMiddle();
            middle.setTransactionId(id);
            redisServer.set(RedisKeysUtils.LOGINNAME,"删除中间表交易对");
            exchangeTransactionpairMiddleService.deleteByTraId(id,middle);
            return new ReturnResult<TransactionPair>(0,"删除成功",1,1);
        }catch (Exception e){
            e.printStackTrace();
            return new ReturnResult<TransactionPair>(-1,"删除失败",1,1);
        }
    }

    /**
     * 交易对批量上传
     * @param file
     * @return
     */
    @ApiOperation(value = "交易对批量上传",notes = "交易对批量上传")
    @PostMapping("uploadFile")
    @ResponseBody
    public Object insBachTra(@RequestParam(value = "file", required = false) MultipartFile file){
        redisServer.set(RedisKeysUtils.LOGINNAME,"交易对批量上传");
        TransactionPair pair = null;
        List success = new ArrayList();//上传成功的交易对
        List failed = new ArrayList();//重复上传的交易对
        Set notFound = new HashSet();//设置失败的货币
        Set setsucc = new HashSet();//设置成功的货币
        int total = 0;
        try {
            if(null != file){
                XSSFWorkbook wb = new XSSFWorkbook(file.getInputStream());
                if(null != wb){
                    XSSFSheet sheet = wb.getSheetAt(0);
                    if(null != sheet){
                        for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                            XSSFRow row = sheet.getRow(i);
                            total = sheet.getLastRowNum();
                            if(null != row){
                                pair = new TransactionPair();
                                String  transactionName = row.getCell(0).getStringCellValue().trim();//币种名称
                                String enName = row.getCell(1).getStringCellValue().trim();//法币名称
                                if(StringUtils.isNotBlank(transactionName) && StringUtils.isNotBlank(enName)){
                                    pair.setEnName(enName);
                                    pair.setTransactionName(transactionName);
                                    //判断交易对表中是否有重复交易对
                                    TransactionPair old = transactionPairService.selectByEntity(pair);
                                    if(null == old){
                                        pair.setCreateTime(new Date());
                                        pair.setUpdateTime(new Date());
                                        transactionPairService.insertTransaction(pair);//添加交易对表记录
                                        success.add(transactionName+"/"+enName);
                                    }else{
                                        failed.add(transactionName+"/"+enName);
                                    }
                                    //查询货币表
                                    CurrencyInfo info = currencyInfoService.selectByEntity(new CurrencyInfo().setSymbol(enName));
                                    if(null != info){
                                        if(null == info.getFrenchCurrency() || !info.getFrenchCurrency()){
                                            info.setFrenchCurrency(true);
                                            info.setUpdateTime(new Date());
                                            currencyInfoService.updateByPrimaryKey(info,info);//修改货币表，将货币设置为法币
                                        }
                                        setsucc.add(enName);
                                    }else{
                                        notFound.add(enName);
                                    }
                                }else{
                                    total--;
                                }
                            }
                        }
                    }
                }
                return new ReturnResult<TransactionPair>(0,
                        "本次共上传"+total+"个交易对，其中"+success.size()+"个上传成功，上传成功的交易对："+success+"；"
                                +failed.size()+"个重复上传，未被录入，重复上传的交易对："+failed+"；成功设置的法币："
                                +setsucc+",没有找到货币："+notFound+"，无法设置为法币。",1,1);
            }else {
                return new ReturnResult<TransactionPair>(1,"文件为空",1,1);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return new ReturnResult<TransactionPair>(-1,
                    "出现未知错误上传中断！本次共上传"+total+"个交易对，其中"+success.size()+"个上传成功，上传成功交易对："+success+"；"
                    +failed.size()+"个重复上传，未被录入，重复上传交易对："+failed+"；成功设置的法币："
                            +setsucc+",没有找到货币："+notFound+"，无法设置为法币。",1,1);
        }
    }
}
